from flask import Flask, jsonify, request  # 添加request导入
from django_test import TeachStudent  # 导入TeachStudent模型
from config.config import get_config

# 获取配置
config = get_config()

app = Flask(__name__)

@app.route('/')
def home():
    return '<h1>Hello, World!</h1>'

@app.route('/api/students')
def get_students():
    # 使用Django模型查询数据
    students = TeachStudent.objects.get(id=1)
    return jsonify({
        "status": "success",
        "data": list(students.values())
    })

# 添加POST方法
@app.route('/api/students', methods=['POST'])
def create_student():
    try:
        # 获取请求数据
        data = request.json
        
        # 数据验证
        if not data.get('name'):
            raise ValueError("Name is required")
            
        # 检查是否已存在
        existing_student = TeachStudent.objects.filter(name=data.get('name')).first()
        if existing_student:
            return jsonify({
                "status": "error",
                "message": "Student with this name already exists"
            }), 400
            
        # 创建新记录
        student = TeachStudent.objects.create(
            name=data.get('name'),
            teach_course_id=data.get('teach_course_id', None)  # 可选字段
        )
        
        # 返回创建的数据
        return jsonify({
            "status": "success",
            "message": "Student created successfully",
            "data": {
                "id": student.id,
                "name": student.name,
                "teach_course_id": student.teach_course_id
            }
        }), 201  # 201表示创建成功
        
    except ValueError as ve:
        return jsonify({
            "status": "error",
            "message": str(ve)
        }), 400
        
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": f"Failed to create student: {str(e)}"
        }), 500

if __name__ == '__main__':
    app.run(
        debug=config['DEBUG'],
        host=config['HOST'],
        port=config['PORT']
    )